import json
import os
import openslide
from tqdm import tqdm


wsi_folder = "/Users/user/Desktop/tt/png"
geo_folder = "/Users/user/Desktop/tt"
out_folder = ""
os.makedirs(out_folder, exist_ok=True)
roi_size = 5000

for geo in tqdm(os.listdir(geo_folder)):
    if not geo.endswith(".geojson"):
        continue
    basename = geo.replace(".geojson", "")
    wsi_path = os.path.join(wsi_folder, basename+".svs")
    geo_path = os.path.join(geo_folder, geo)
    geo_data = json.load(open(geo_path))
    x, y = geo_data["features"][0]["geometry"]["coordinates"][0][0]
    slide = openslide.open_slide(wsi_path)
    crop_roi = slide.read_region((x, y), 0, (roi_size, roi_size)).convert("RGB")
    crop_roi.save(f"{out_folder}/{basename}.png")

